const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const { pool } = require('../config/db.js')
const { generateVerifyCode, sendVerifyCode } = require('../config/email.js')
const { setVerifyCode, getVerifyCode, deleteVerifyCode } = require('../services/redis.js')
const { auth } = require('../middlewares/auth.js')

// 注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, password, verifyCode } = req.body

    // 验证必填字段
    if (!username || !email || !password || !verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '所有字段都是必填的',
        success: false
      })
    }

    // 验证验证码
    const storedCode = await getVerifyCode(email)
    if (!storedCode || storedCode !== verifyCode) {
      return res.status(400).json({
        code: 400,
        message: '验证码错误或已过期',
        success: false
      })
    }

    const connection = await pool.getConnection()
    try {
      // 检查用户是否已存在
      const [existingUsers] = await connection.query(
        'SELECT id FROM users WHERE username = ? OR email = ?',
        [username, email]
      )

      if (existingUsers.length > 0) {
        return res.status(400).json({
          code: 400,
          message: '用户名或邮箱已存在',
          success: false
        })
      }

      // 加密密码
      const salt = await bcrypt.genSalt(10)
      const hashedPassword = await bcrypt.hash(password, salt)

      // 创建用户
      const [result] = await connection.query(
        'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
        [username, email, hashedPassword]
      )

      // 删除验证码
      await deleteVerifyCode(email)

      // 生成JWT
      const token = jwt.sign(
        { userId: result.insertId },
        process.env.JWT_SECRET || 'your-jwt-secret',
        { expiresIn: '24h' }
      )

      res.status(201).json({
        code: 201,
        message: '注册成功',
        success: true,
        data: {
          token,
          user: {
            id: result.insertId,
            username,
            email,
            theme: 'dark',
            model: 'deepseek-chat',
            temperature: 0.7
          }
        }
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    console.error('注册错误:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body

    if (!username || !password) {
      return res.status(400).json({
        code: 400,
        message: '用户名和密码不能为空',
        success: false
      })
    }

    const connection = await pool.getConnection()
    try {
      // 查找用户
      const [users] = await connection.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
      )

      if (users.length === 0) {
        return res.status(401).json({
          code: 401,
          message: '用户名或密码错误',
          success: false
        })
      }

      const user = users[0]

      // 验证密码
      const isMatch = await bcrypt.compare(password, user.password)
      if (!isMatch) {
        return res.status(401).json({
          code: 401,
          message: '用户名或密码错误',
          success: false
        })
      }

      // 生成JWT
      const token = jwt.sign(
        { userId: user.id },
        process.env.JWT_SECRET || 'your-jwt-secret',
        { expiresIn: '24h' }
      )

      // 排除密码
      const { password: _, ...userWithoutPassword } = user

      res.json({
        code: 200,
        message: '登录成功',
        success: true,
        data: {
          token,
          user: userWithoutPassword
        }
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    console.error('登录错误:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 发送验证码
router.post('/send-code', async (req, res) => {
  try {
    const { email } = req.body

    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '邮箱不能为空',
        success: false
      })
    }

    const verifyCode = generateVerifyCode()
    const sendResult = await sendVerifyCode(email, verifyCode)

    if (!sendResult) {
      return res.status(500).json({
        code: 500,
        message: '验证码发送失败',
        success: false
      })
    }

    await setVerifyCode(email, verifyCode)

    res.json({
      code: 200,
      message: '验证码已发送',
      success: true
    })
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 获取用户信息
router.get('/:id', auth, async (req, res) => {
  try {
    const connection = await pool.getConnection()
    try {
      const [users] = await connection.query(
        'SELECT id, username, email, api_key, theme, model, temperature, created_at, updated_at FROM users WHERE id = ?',
        [req.params.id]
      )

      if (users.length === 0) {
        return res.status(404).json({
          code: 404,
          message: '用户不存在',
          success: false
        })
      }

      res.json({
        code: 200,
        message: '获取成功',
        success: true,
        data: users[0]
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

module.exports = router
